#include "stdio.h"
#include "main.h"
#include "gpio.h"

static int is_put_water = 0;

#define LED_GREEN_ENABLE()                HAL_GPIO_WritePin(LED_GREEN_GPIO_Port, LED_GREEN_Pin, GPIO_PIN_RESET)
#define LED_GREEN_DISABLE()               HAL_GPIO_WritePin(LED_GREEN_GPIO_Port, LED_GREEN_Pin, GPIO_PIN_SET)
#define LED_GREEN_TOGGLE()                HAL_GPIO_TogglePin(LED_GREEN_GPIO_Port, LED_GREEN_Pin)

#define PUT_WATER_ENABLE()                HAL_GPIO_WritePin(WATER_ENABLE_GPIO_Port, WATER_ENABLE_Pin, GPIO_PIN_RESET)
#define PUT_WATER_DISABLE()               HAL_GPIO_WritePin(WATER_ENABLE_GPIO_Port, WATER_ENABLE_Pin, GPIO_PIN_SET)

#define BEEP_ENABLE()                     HAL_GPIO_WritePin(BEEP_GPIO_Port, BEEP_Pin, GPIO_PIN_SET)
#define BEEP_DISABLE()                    HAL_GPIO_WritePin(BEEP_GPIO_Port, BEEP_Pin, GPIO_PIN_RESET)

int is_putting_water()
{
  return is_put_water;
}

int gpio_init()
{
  LED_RED_DISABLE();
  LED_GREEN_DISABLE();
  PUT_WATER_DISABLE();
  BEEP_DISABLE();
  
  return 0;
}

void gpio_loop()
{
  GPIO_PinState gpio0 = HAL_GPIO_ReadPin(WATER_CHECK_0_GPIO_Port, WATER_CHECK_0_Pin);
  GPIO_PinState gpio1 = HAL_GPIO_ReadPin(WATER_CHECK_1_GPIO_Port, WATER_CHECK_1_Pin);
  
  //printf("Water %d - %d\n",gpio0,gpio1);
  
  if (is_put_water) {
    if (gpio0 == GPIO_PIN_SET && gpio1 == GPIO_PIN_SET) {
      printf("put water over\n");
      PUT_WATER_DISABLE();
      is_put_water = 0;
    }
  } else {
    if (gpio0 == GPIO_PIN_RESET && gpio1 == GPIO_PIN_RESET) {
      printf("put water start\n");
      PUT_WATER_ENABLE();
      is_put_water = 1;
    }
  }
  {
    static uint32_t tick_last = 0;
    if (is_put_water) {
      uint32_t tick_now = HAL_GetTick();
      if (tick_now - tick_last >= 100) {
        LED_GREEN_TOGGLE();
        tick_last = tick_now;
      }
    } else {
      LED_GREEN_DISABLE();
    }
  }
}

void gpio_error()
{
  while (1) {
    HAL_Delay(200);
    BEEP_ENABLE();
    HAL_Delay(200);
    BEEP_DISABLE();
  }
}
